package com.talent.jiwen.my;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.EvaluateTagListResult;
import com.talent.jiwen.http.result.PayInfo;
import com.talent.jiwen.teacher.CourseAllListFragment;
import com.talent.jiwen.teacher.OrderAppealActivity;
import com.talent.jiwen.ui.widgets.StarBar;
import com.talent.jiwen.ui.widgets.flowlayout.FlowLayout;
import com.talent.jiwen.ui.widgets.flowlayout.TagAdapter;
import com.talent.jiwen.ui.widgets.flowlayout.TagFlowLayout;
import com.talent.jiwen.util.CommonUtils;
import com.talent.jiwen.util.DateUtils;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.LogUtil;
import com.talent.jiwen.util.MaterialDialogUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;

public class EvaluateActivity extends BaseActivity {
    @BindView(R.id.submitTv)
    TextView submitTv;
    @BindView(R.id.teacherIv)
    ImageView teacherIv;
    @BindView(R.id.nameTv)
    TextView nameTv;
    @BindView(R.id.useTimeTv)
    TextView useTimeTv;
    @BindView(R.id.solvedTv)
    TextView solvedTv;
    @BindView(R.id.unSolvedTv)
    TextView unSolvedTv;
    @BindView(R.id.effectRatingBar)
    StarBar effectRatingBar;//互动性
    @BindView(R.id.serviceRatingBar)
    StarBar serviceRatingBar;//趣味性
    @BindView(R.id.contentEt)
    EditText contentEt;
    @BindView(R.id.tagLayout)
    TagFlowLayout tagLayout;
    @BindView(R.id.starLayout)
    LinearLayout startLayout;
    @BindView(R.id.reasonLayout)
    LinearLayout reasonLayout;
    @BindView(R.id.sadTv)
    TextView sadTv;
    @BindView(R.id.busyTv)
    TextView busyTv;

    private int solveStatus = 1;//1、已解决 ， 9、未解决
    private String notAppealReason = "";
    private static final String REASON_BAD = "心灰意冷";
    private static final String REASON_BUSY = "不想找事";

    private String orderId;
    private String teacherId;
    private static final String PARAM_ORDER_ID = "param.order.id";
    private static final String PARAM_TEACHER_ID = "param.teacher.id";

    private List<EvaluateTagListResult.EvaluateTag> tagList = new ArrayList<>();
    private TagAdapter<EvaluateTagListResult.EvaluateTag> tagAdapter;



    @Override
    protected int provideContentViewId() {
        return R.layout.activity_evaluate;
    }

    @Override
    public String titleName() {
        return getString(R.string.evaluate);
    }

    @Override
    protected void initData() {
        effectRatingBar.setIntegerMark(true);
        serviceRatingBar.setIntegerMark(true);

        orderId = getIntent().getStringExtra(PARAM_ORDER_ID);
        teacherId = getIntent().getStringExtra(PARAM_TEACHER_ID);

        tagAdapter = new TagAdapter<EvaluateTagListResult.EvaluateTag>(tagList) {
            @Override
            public View getView(FlowLayout parent, int position, final EvaluateTagListResult.EvaluateTag evaluateTag) {
                final TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tv_tag,
                        tagLayout, false);
                tv.setText(evaluateTag.getTagName());

//                tv.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        if (tagLayout.getSelectedList().size() == 3){
//                            showToast("最多选择3个标签");
//                        }else{
//                            tv.setSelected(true);
//                        }
//                    }
//                });

                return tv;
            }
        };
        tagLayout.setAdapter(tagAdapter);

        getOrderDetail(orderId);
        getEvaluationTagList();


    }

    @OnClick({R.id.submitTv, R.id.solvedTv, R.id.unSolvedTv, R.id.sadTv, R.id.busyTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.submitTv:
                String content = contentEt.getText().toString();
                if (Validators.isEmpty(content)){
                    showToast("请填写评价信息");
                }else{
                    saveCustomerEvaluation(content);
                }
                break;
            case R.id.solvedTv:
                startLayout.setVisibility(View.VISIBLE);
                reasonLayout.setVisibility(View.GONE);
                solveStatus = 1;
                notAppealReason = "";
                solvedTv.setBackgroundResource(R.drawable.bg_circle_theme);
                solvedTv.setTextColor(ContextCompat.getColor(this , R.color.white));
                unSolvedTv.setBackgroundResource(R.drawable.bg_empty_circle_gray);
                unSolvedTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                break;
            case R.id.unSolvedTv:
                solveStatus = 9;
                notAppealReason = "";
                MaterialDialog.Builder dialog = MaterialDialogUtil.getCommonDialog(this, "提示", "是否发起申诉", "确定", "取消", new MaterialDialogUtil.OnDialogPoNeClickListener() {
                    @Override
                    public void onPositive() {
                        OrderAppealActivity.startOrderAppealActivity(EvaluateActivity.this , OrderAppealActivity.APPEAL_ORDER , orderId);
                        finish();
                    }

                    @Override
                    public void onNegative() {
                        startLayout.setVisibility(View.GONE);
                        reasonLayout.setVisibility(View.VISIBLE);
                    }
                });
                dialog.show();

                solvedTv.setBackgroundResource(R.drawable.bg_empty_circle_gray );
                solvedTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                unSolvedTv.setBackgroundResource(R.drawable.bg_circle_theme);
                unSolvedTv.setTextColor(ContextCompat.getColor(this , R.color.white));
                break;
            case R.id.sadTv:
                notAppealReason = REASON_BAD;

                sadTv.setBackgroundResource(R.drawable.bg_circle_theme);
                sadTv.setTextColor(ContextCompat.getColor(this , R.color.white));
                busyTv.setBackgroundResource(R.drawable.bg_empty_circle_gray);
                busyTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                break;
            case R.id.busyTv:
                notAppealReason = REASON_BUSY;

                sadTv.setBackgroundResource(R.drawable.bg_empty_circle_gray );
                sadTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                busyTv.setBackgroundResource(R.drawable.bg_circle_theme);
                busyTv.setTextColor(ContextCompat.getColor(this , R.color.white));
                break;
        }
    }

    /**获取订单信息
     *
     * @param orderId
     */
    private void getOrderDetail(String orderId) {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("studentId", SPUtil.getUserId());
        Observable observable = ApiFactory.getEducationApiSingleton().getOrderPayInfo(SPUtil.getToken(),map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<PayInfo>(this) {
            @Override
            protected void _onNext(PayInfo payInfo) {
                if (payInfo != null) {
                    ImageUtil.loadCornerImageWithDefault(EvaluateActivity.this,payInfo.getOrderPayInfo().getTeacherHeadImage(),R.mipmap.default_img, 4 , teacherIv);
                    nameTv.setText(payInfo.getOrderPayInfo().getTeacherName());
                    try {
                        useTimeTv.setText("课程用时"+ DateUtils.getDatePoor(Long.parseLong(payInfo.getOrderPayInfo().getEndTime())-Long.parseLong(payInfo.getOrderPayInfo().getStartTime())));
                    }catch (Exception e){
                        LogUtil.e(e.toString());
                    }
                } else {
                    showToast(getString(R.string.data_is_wrong));
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }

    /**保存评价信息
     *
     * @param content
     */
    private void saveCustomerEvaluation(String content){
        Map<String, String> map = new HashMap<>();
        map.put("teacherId" , teacherId);
        map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId" , orderId);
        map.put("commentDetail" , content);
        map.put("commentImage" , "");
        map.put("solveStatus" , solveStatus + "");

        if (solveStatus == 1){
            //已解决
            map.put("serveScore" , (int)(serviceRatingBar.getStarMark()) + "");
            map.put("effectScore" , (int)(effectRatingBar.getStarMark()) + "");
        }else{
            //未解决,评价分传1
            map.put("serveScore" , "1");
            map.put("effectScore" , "1");
            //不申诉原因
            map.put("rejectAppealReason" , notAppealReason);
        }


        Set<Integer> selectSet = tagLayout.getSelectedList();
        if (null != selectSet && selectSet.size() != 0){
            StringBuilder sb = new StringBuilder();
            for (Integer i : selectSet){
                sb.append(tagList.get(i).getTagId());
                sb.append(",");
            }
            sb.deleteCharAt(sb.length() - 1);

            LogUtil.e("标签信息===" + sb.toString());

            map.put("tag" , sb.toString());
        }

        Observable observable = ApiFactory.getEducationApiSingleton().saveCustomerEvaluation(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(this) {
            @Override
            protected void _onNext(Void v) {
                EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
                finish();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }

    /**学生评价时，获取标签列表
     *
     */
    private void getEvaluationTagList(){
        Observable observable = ApiFactory.getEducationApiSingleton().getEvaluationTagList(SPUtil.stringOut(SPConstant.TOKEN));
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<EvaluateTagListResult>(this) {
            @Override
            protected void _onNext(final EvaluateTagListResult result) {
                tagList.clear();
                tagList.addAll(result.getTagList());
                tagAdapter.notifyDataChanged();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);

    }

    /**启动该页面
     *
     * @param context
     * @param orderId
     */
    public static void startEvaluateActivity(Context context , String orderId , String teacherId){
        Intent intent = new Intent();
        intent.setClass(context , EvaluateActivity.class);
        intent.putExtra(PARAM_ORDER_ID , orderId);
        intent.putExtra(PARAM_TEACHER_ID , teacherId);
        context.startActivity(intent);
    }

}
